package com.ifar.audiosdk

import android.app.Application
import android.content.Context
import com.blankj.utilcode.util.Utils
import com.ifar.audiosdk.model.engine.CurrentUserSettings
import com.ifar.audiosdk.model.engine.MyEngineEventHandler
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import io.agora.rtc.Constants
import io.agora.rtc.RtcEngine
import kotlin.properties.Delegates

/**
 * 基础baseApp
 */
open class IfarBaseApp : Application() {
    private val mVideoSettings: CurrentUserSettings = CurrentUserSettings()

    private lateinit var mRtcEngine: RtcEngine
    private var mEventHandler: MyEngineEventHandler = MyEngineEventHandler()

    open fun rtcEngine(): RtcEngine {
        return mRtcEngine
    }

    open fun userSettings(): CurrentUserSettings {
        return mVideoSettings
    }

    companion object {
        var CONTEXT: Context by Delegates.notNull()
        var APP_IFAR: IfarBaseApp by Delegates.notNull()
    }

    override fun onCreate() {
        super.onCreate()
        CONTEXT = this.applicationContext
        APP_IFAR = this

        initLogger()
        Utils.init(APP_IFAR)
        createRtcEngine()
    }

    private fun initLogger() {
        val formatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(false)
            .methodCount(0)
            .methodOffset(7)
            .tag("ifar_logger")
            .build()

        Logger.addLogAdapter(AndroidLogAdapter(formatStrategy))
    }

    private fun createRtcEngine() {
        val context = applicationContext
        val appId = context.getString(R.string.agora_app_id)
        mRtcEngine = try {
            RtcEngine.create(context, appId, mEventHandler)
        } catch (e: Exception) {
            throw RuntimeException()
        }
        mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING)
        mRtcEngine.enableVideo()
        mRtcEngine.enableDualStreamMode(true)
        mRtcEngine.switchCamera()
    }
}